import React, {useEffect, useRef, useState} from 'react'
// @ts-ignore
import styles from './index.less'
import {EditableForm} from "@/components/EditableFormField";
import {Button, Input, message, Modal, Select, Tag, TreeSelect} from "antd";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {isSuccess, isSuccessful} from "@/utils/utils";
import {TableListItem} from "@/utils/constants";
// @ts-ignore
import {OperateSystem} from "@/services/api-functions";
import CreateForm from "@/components/CreateForm/CreateForm";

interface UserDetailProps {
  user: any,
  allRoleList: any[],
  refresh: () => {}
}

const UserDetail: React.FC<UserDetailProps> = ({ user, allRoleList, refresh}) => {

  const actionRef = useRef<ActionType>();
  const [userDetail, setUserDetail] = useState<any>(user);
  const [addVisible, setAddVisible] = useState<any>(false);

  useEffect(() => {
    queryUserDetail().then();
    actionRef.current?.reload();
  }, [user])

  const setUserProperty = (name:any, value:any) => {
    if (user) {
      OperateSystem.updateSysUserByProperty(user.id, {name, value}).then(async (res: any) => {
        if (isSuccessful(res)) {
          await queryUserDetail();
          refresh && typeof refresh==="function" && refresh();
        }
      })
    }
  }

  const queryUserDetail = async () =>{
    let {data, code}:any = await OperateSystem.getQueryUserDetail(user.id);
    if(isSuccess(code)){
      setUserDetail(data)
    }
    let base = data?.supperAdmin ? [{id:-1,role:{id: -1, name: '超级管理员', description: '系统默认角色，不可编辑删除'}}] : []
    return {
      data: [...base, ...(isSuccess(code) ? data.userRoles : [])],
      success: isSuccess(code),
      total: (data?.supperAdmin ? 1 : 0) + (isSuccess(code) ? data.userRoles.length : 0)
    };
  }

  const columns: ProColumns<any>[] = [
    {
      title: '角色',
      dataIndex: 'roleId',
      hideInTable: true,
      hideInSearch: true,
      valueType: "select",
      formItemProps: {rules:[{ required: true}],},
      renderFormItem: (schema, config) => <TreeSelect
        value={config.value}
        treeData={allRoleList}
        placeholder="请选择角色"
        treeDefaultExpandAll
      />
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      width: 250,
      ellipsis: true,
      hideInForm: true,
      render: (_, record) => record.role.name
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInForm: true,
      render: (_, record) => record.role.description||'暂无描述',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width:100,
      render: (_, record) => record.id > 0 ? [
        <a style={{color: "red"}} onClick={() => Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined/>,
          content: <span>确定要删除 <Tag color='#108ee9'>{userDetail.name}</Tag> 的 <Tag color='red'>{record.role.name}</Tag> 角色吗？</span>,
          okText: '删除',
          cancelText: '取消',
          onOk: () => {
            OperateSystem.deleteUserRole(record.id, user.id).then((resp: any) => {
              if (isSuccessful(resp)) {
                message.success('删除成功', 1, () => {
                  actionRef.current?.reload();
                  refresh && typeof refresh==="function" && refresh();
                })
              }
            })
          },
        })}>删除</a>,
      ] : [],
    },
  ];

  return <>
    <div className={styles.title}>
      <span>基本信息</span>
      <div className={styles.flexFill} />
    </div>
    <div className={styles.form}>
      <div className={styles.formItem}>
        <div className={styles.itemLabel}>姓名<span className={styles.warn}> *</span></div>
        <div className={styles.itemInput}>
          <EditableForm value={userDetail.name} placeholder='请输入姓名' onChange={value=>setUserProperty('name', value)}>
            <Input placeholder='请输入姓名'/>
          </EditableForm>
        </div>
      </div>
      <div className={styles.formItem}>
        <div className={styles.itemLabel}>昵称<span className={styles.warn}> *</span></div>
        <div className={styles.itemInput}>
          <EditableForm value={userDetail.nickName} placeholder='请输入昵称' onChange={value=>setUserProperty('nickName', value)}>
            <Input placeholder='请输入昵称'/>
          </EditableForm>
        </div>
      </div>
      <div className={styles.formItem}>
        <div className={styles.itemLabel}>手机号<span className={styles.warn}> *</span></div>
        <div className={styles.itemInput}>
          <EditableForm value={userDetail.cellphone} placeholder='请输入手机号' onChange={value=>setUserProperty('cellphone', value)}>
            <Input placeholder='请输入手机号'/>
          </EditableForm>
        </div>
      </div>
      <div className={styles.formItem}>
        <div className={styles.itemLabel}>邮箱<span className={styles.warn}> *</span></div>
        <div className={styles.itemInput}>
          <EditableForm value={userDetail.email} placeholder='请输入邮箱' onChange={value=>setUserProperty('email', value)}>
            <Input placeholder='请输入邮箱'/>
          </EditableForm>
        </div>
      </div>
      <div className={styles.formItem}>
          <div className={styles.itemLabel}>
            是否可登录
          </div>
          <div className={styles.itemInput}>
            <Select style={{width: '100%'}} onSelect={(value: any) => setUserProperty('loginAdmin', value)}
                    value={userDetail.loginAdmin ? 1 : 0}>
              <Select.Option value={1}>可登录</Select.Option>
              <Select.Option value={0}>不可登录</Select.Option>
            </Select>
          </div>
        </div>

    </div>
    <div className={styles.title}>
      <span>用户角色</span>
      <div className={styles.flexFill} />
    </div>
    <ProTable<any>
      headerTitle={`${userDetail.name} 角色`}
      actionRef={actionRef}
      rowKey="id"
      search={false}
      toolBarRender={() => [
        <Button type="primary" onClick={() => setAddVisible(true)}>
          <PlusOutlined /> 添加角色
        </Button>,
      ]}
      request={() => queryUserDetail()}
      columns={columns}
    />
    <CreateForm onCancel={() => setAddVisible(false)} title={`${user.name} 添加权限`} modalVisible={addVisible}>
      <ProTable<TableListItem, TableListItem>
        onSubmit={async (value: any) => {
          const resp = await OperateSystem.addUserRole(value.roleId, user.id);
          if (isSuccessful(resp)) {
            setAddVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
              refresh && typeof refresh==="function" && refresh();
            }
          }
        }}
        rowKey="key"
        type="form"
        columns={columns}
      />
    </CreateForm>
  </>
};


export default UserDetail;
